"""

.. module:: showspaces_service
.. moduleauthor:: @author: 

*Description*:

This module contains the ShowSpacesService class.

*Constants*:

.. seealso:: class :class:`runtime.service.Service`
"""

# Imports
#
import datetime
import threading
import time
import logging

from datastore.resource import *
from datastore.uri import *
from runtime.service import *
from runtime.node import LoggingLevels

# Constants
#

# Classes
#

class ShowSpacesService(Service):
    """
    **Constants**:
    """
    
    def cb_start(self, uri, action, res):
        """
        :param uri: Uri
        :param action:
        :param res: Resource
        """
        
        self.logger.log(logging.DEBUG, 
            "Show Spaces available at (%s)", self.service_def.api.fetch.uri)
        self.spaces.set_process(self.service_def.api.fetch.uri, self.cb_process)
        self.spaces.set_process(self.service_def.api.all.uri, self.cb_show_all)

    def cb_process(self, uri, action, res):
        """
        :param uri: Uri
        :param action:
        :param res: Resource
        """
        
        spaces_uri = Uri(str(uri.full())[len(self.service_def.api.fetch.uri):])
        self.logger.log(logging.DEBUG, 
            "Action (%s) uri (%s)", action, str(spaces_uri))
        if action == 'exists':
            if spaces_uri.is_collection() or (len(spaces_uri) == 0):
                coll = {}
                for u in self.spaces.find(spaces_uri):
                    sp = str(u.full())[len(spaces_uri):].split('/', 1)
                    if len(sp) == 1:
                        coll[sp[0]] = True
                    else:
                        coll[sp[0] + '/'] = True
                return len(coll.keys()) > 0
            else:
                return self.spaces.exists(spaces_uri)
        elif action == 'get':
            if spaces_uri.is_collection() or (len(spaces_uri) == 0):
                # create a list of the next level of uri's and collection's.
                coll = {}
                for u in self.spaces.find(spaces_uri):
                    if len(spaces_uri) == 0:
                        sp = u.split()
                        coll[str(Uri(sp[0]).shorten())] = True
                    else: 
                        sp = str(u.full())[len(spaces_uri):].split('/', 1)
                        if len(sp) == 1:
                            coll[sp[0]] = True
                        else:
                            coll[sp[0] + '/'] = True
                coll_list = coll.keys()
                res = Resource(type='term:base/services/http/response')
                res.content_type = "text/html"
                res.content = "<h1>Admin - View spaces for '%s'</h1>" % spaces_uri
                for u in sorted(coll_list):
                    res.content += """<a href="%s">%s</a><br />""" % \
                        ('/admin/spaces/' + str(spaces_uri) + u, 
                         str(spaces_uri + u))
                res.content_length = len(res.content)
                return res
            else:
                self.logger.log(logging.DEBUG, 
                                "get returns uri (%s)", str(spaces_uri))
                # prevent DeserialisationException exceptions
                return self.spaces.get(spaces_uri, copy=False)
        elif action == 'delete':
            self.logger.log(logging.DEBUG, 
                            "delete (%s)", str(spaces_uri))
            return self.spaces.delete(spaces_uri)
        elif action == 'put':
            self.logger.log(logging.DEBUG, 
                            "put (%s)", str(spaces_uri))
            return self.spaces.put(spaces_uri, res)
    
    def cb_show_all(self, uri, action, res):
        """
        :param uri: Uri
        :param action:
        :param res: Resource
        """
        
        if action == 'exists':
            return True
        elif action == 'get':
            res = Resource(type='term:base/services/http/response')
            res.content_type = "text/html"
            res.content = "<h1>Admin - View all Resources</h1>"
            all = self.spaces.find(Uri())
            for u in sorted(all):
                res.content += """<a href="%s">%s</a> <small>[<a href="%s?diag=raw">raw</a>]</small><br />""" % \
                    ('/admin/spaces/' + str(u.shorten()), 
                     str(u.shorten()), '/admin/spaces/' + str(u.shorten()))
            res.content_length = len(res.content)
            return res
